<template>
  <div class="app-container">
    <!-- 去除顶部搜索表单 -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:assessConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:assessConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:assessConfig:remove']"
        >删除</el-button>
      </el-col>
      <!-- 去除导出和右侧工具栏 -->
    </el-row>

    <el-table v-loading="loading" :data="assessConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="被考核人角色" align="center" prop="assessRole" :formatter="formatRoleName" />
      <el-table-column label="管理者角色" align="center" prop="managerRole" :formatter="formatRoleName" />
      <el-table-column label="提交天数限制" align="center" prop="day" />
      <el-table-column label="权重" align="center" prop="weight" :formatter="formatWeight" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:assessConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:assessConfig:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考核配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="被考核人角色" prop="assessRole">
          <el-select v-model="form.assessRole" placeholder="请选择" filterable clearable style="width:100%" @change="checkWeightTotal">
            <el-option v-for="role in roleOptions" :key="role.roleId" :label="role.roleName" :value="role.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理者角色" prop="managerRole">
          <el-select v-model="form.managerRole" placeholder="请选择" filterable clearable style="width:100%">
            <el-option v-for="role in roleOptions" :key="'m-'+role.roleId" :label="role.roleName" :value="role.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交天数限制" prop="day">
          <el-input v-model="form.day" placeholder="请输入提交天数限制" />
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-input-number 
            v-model="form.weight" 
            :min="0" 
            :max="100" 
            :precision="0"
            placeholder="请输入权重百分比" 
            style="width:100%"
            controls-position="right"
            @change="checkWeightTotal"
          >
            <template slot="append">%</template>
          </el-input-number>
          <div v-if="form.assessRole && form.weight" class="weight-tip">
            <span :class="weightTotalClass">
              当前该角色权重总和: {{ currentWeightTotal }}%
              <span v-if="currentWeightTotal > 100" class="weight-warning">(超过100%限制)</span>
            </span>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button 
          type="primary" 
          @click="submitForm"
          :disabled="isSubmitDisabled"
        >{{ submitButtonText }}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAssessConfig, getAssessConfig, delAssessConfig, addAssessConfig, updateAssessConfig } from "@/api/system/assessConfig"
import { listRole } from "@/api/system/role"

export default {
  name: "AssessConfig",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件（已移除搜索，不再使用）
      showSearch: false,
      // 总条数
      total: 0,
      // 考核配置表格数据
      assessConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数（去除具体搜索字段，仅分页）
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 角色选项
      roleOptions: [],
      // 角色映射表 { roleId: roleName }
      roleMap: {},
      // 权重详情
      weightDetails: [],
      // 当前权重总和
      currentWeightTotal: 0,
      // 表单校验
      rules: {
        assessRole: [{ required: true, message: '请选择被考核人角色', trigger: 'change' }],
        managerRole: [{ required: true, message: '请选择管理者角色', trigger: 'change' }],
        day: [{ required: true, message: '请输入提交天数限制', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入权重', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 提交按钮是否禁用
    isSubmitDisabled() {
      return this.currentWeightTotal > 100
    },
    // 提交按钮文本
    submitButtonText() {
      return this.isSubmitDisabled ? "权重总和超过100%" : "确 定"
    }
  },
  created() {
    // 先拉取角色以便表格格式化展示
    this.fetchRoles().then(() => {
      this.getList()
    })
  },
  methods: {
    /** 查询考核配置列表 */
    getList() {
      this.loading = true
      listAssessConfig(this.queryParams).then(response => {
        this.assessConfigList = response.rows
        this.total = response.total
        this.loading = false
        // 确保角色映射表已加载
        if (Object.keys(this.roleMap).length === 0) {
          this.fetchRoles()
        }
      }).catch(error => {
        this.loading = false
        console.error('获取考核配置列表失败:', error)
      })
    },
    // 拉取所有角色
    fetchRoles() {
      return listRole({ pageNum: 1, pageSize: 1000 }).then(res => {
        const rows = res.rows || []
        this.roleOptions = rows
        const map = {}
        rows.forEach(r => { 
          if (r.roleId && r.roleName) {
            map[r.roleId] = r.roleName 
          }
        })
        this.roleMap = map
        console.log('角色映射表已加载:', this.roleMap) // 调试信息
        console.log('角色数据:', rows) // 查看原始角色数据
      }).catch(error => {
        console.error('加载角色数据失败:', error)
        this.roleMap = {}
      })
    },
    // 表格显示角色名
    formatRoleName(row, column, cellValue) {
      if (cellValue == null || cellValue === '') return '-'
      // 如果角色映射表还没有加载，返回原始值
      if (Object.keys(this.roleMap).length === 0) {
        console.log('角色映射表为空，返回原始值:', cellValue)
        return cellValue
      }
      const roleName = this.roleMap[cellValue]
      if (!roleName) {
        console.log('未找到角色ID对应的名称:', cellValue, '当前映射表:', this.roleMap)
        return `角色ID: ${cellValue}`
      }
      return roleName
    },
    // 表格显示权重
    formatWeight(row, column, cellValue) {
      if (cellValue == null) return '-'
      return `${cellValue}%`
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        assessRole: null,
        managerRole: null,
        day: null,
        weight: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.fetchRoles()
      this.open = true
      this.title = "添加考核配置"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAssessConfig(id).then(response => {
        this.form = response.data
        this.fetchRoles()
        this.open = true
        this.title = "修改考核配置"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 验证权重是否合理
          if (this.form.weight < 0 || this.form.weight > 100) {
            this.$modal.msgError("权重必须在0-100之间")
            return
          }
          
          // 验证权重总和是否超过100%
          if (this.currentWeightTotal > 100) {
            this.$modal.msgError("该被考核人角色的权重总和不能超过100%，当前总和：" + this.currentWeightTotal + "%")
            return
          }
          
          if (this.form.id != null) {
            updateAssessConfig(this.form).then(() => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError(error.message || "修改失败")
            })
          } else {
            addAssessConfig(this.form).then(() => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              this.$modal.msgError(error.message || "新增失败")
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除考核配置编号为"' + ids + '"的数据项？').then(function() {
        return delAssessConfig(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 检查权重总和
    checkWeightTotal() {
      if (!this.form.assessRole || !this.form.weight) {
        this.currentWeightTotal = 0
        return
      }
      
      // 计算当前角色的权重总和
      let total = 0
      this.assessConfigList.forEach(item => {
        if (item.assessRole === this.form.assessRole) {
          // 如果是修改操作，排除当前记录
          if (this.form.id && item.id === this.form.id) {
            return
          }
          if (item.weight) {
            total += item.weight
          }
        }
      })
      
      // 加上当前表单的权重
      total += this.form.weight
      this.currentWeightTotal = total
    },
    // 获取权重总和样式类
    get weightTotalClass() {
      return {
        'weight-total': true,
        'weight-exceeded': this.currentWeightTotal > 100
      }
    }
  }
}
</script>

<style scoped>
.weight-tip {
  margin-top: 5px;
  font-size: 12px;
}

.weight-total {
  color: #409EFF;
}

.weight-total.weight-exceeded {
  color: #F56C6C;
}

.weight-warning {
  color: #F56C6C;
  font-weight: bold;
}
</style>
